#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/9 9:17
# @Author : luhongxuan
# @Site :
# @File : auth.py
# @Software: PyCharm

from urllib.parse import parse_qs

from channels.db import database_sync_to_async
from asgiref.sync import sync_to_async
from channels.auth import AuthMiddlewareStack, UserLazyObject
from channels.middleware import BaseMiddleware
from rest_framework_jwt.authentication import jwt_decode_handler

# from apps.user_manager.models import UserProfile


class TokenGetAuthMiddleware(BaseMiddleware):

    def populate_scope(self, scope):
        # Make sure we have a session
        # Add it to the scope if it's not there already
        if "user" not in scope:
            scope["user"] = UserLazyObject()

    async def resolve_scope(self, scope):
        scope["user"]._wrapped = await get_user(scope)


@database_sync_to_async
def get_user(scope):
    params = parse_qs(scope["query_string"])
    if b"token" in params:
        try:
            user_info = jwt_decode_handler(params.get(b'token')[0].decode())
            user_name = user_info.get('username')
            # return UserProfile.objects.filter(username=user_name).first()

        except Exception as e:
            print(e)
            pass

    return None


TokenGetAuthMiddlewareStack = lambda inner: TokenGetAuthMiddleware(
    AuthMiddlewareStack(inner)
)
